package xyz.haijin.spider.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

/**
 * @Author liuhaijin
 * @Date 2022/3/30
 */
public class StringUtil {
    public   static   String StringFilter(String   str)   throws PatternSyntaxException {
        // 只允许字母和数字
        // String   regEx = "[^a-zA-Z0-9]";
        // 清除掉所有特殊字符
        String regEx="[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Pattern p   =   Pattern.compile(regEx);
        Matcher m   =   p.matcher(str);
        return   m.replaceAll("").trim();
    }

    // 截取指定字符后的字符
    public static String getStringAfterKey(String str, String key) {
        return getStringAfterKey(str, key, 0);
    }

    // 截取指定字符后的字符
    public static String getStringAfterKey(String str, String key, int fromIndex) {
        if(str != null && key != null) {
            str = str.substring(str.indexOf(key, fromIndex) + key.length());
        }
        return str;
    }

    // 截取指定字符之间字符
    public static String getStringBetweenLastKeys(String str, String first, String second) {
        if(str != null && first != null && second != null) { // 判断有参数不为空
            // 判断第一个查找串位置
            int firstIndex = str.lastIndexOf(first);
            if(firstIndex != -1 && first.equals(second)) {
                firstIndex = str.lastIndexOf(first, firstIndex - first.length());
            }
            if(firstIndex != -1) {
                firstIndex += first.length();
                int secondIndex = str.indexOf(second, firstIndex);
                if(secondIndex == -1) {
                    secondIndex = str.length();
                }
                str = str.substring(firstIndex, secondIndex);
            }
        }
        return str;
    }


}
